<?php
/**
 * Created by PhpStorm.
 * User: ADMIN
 * Date: 2021/5/24
 * Time: 6:17
 */
namespace applets;

class Applets
{
    private $appid;
    private $appsecret;
    private $code;
    protected $_error = '';

    public function __construct()
    {
        $this->code = ErrorCode::$code;
        $this->appid = config('site.applets_appid');
        $this->appsecret = config('site.applets_appsecret');
        if(empty($this->appid) || empty($this->appsecret))
        {
            $this->_error = $this->code['40001'];
            return false;
        }
    }

    /**
     * 设置错误信息
     * @param $error
     * @return $this
     */
    public function setError($error)
    {
        $this->_error = $error;
        return $this;
    }

    /**
     * 获取错误信息
     * @return string
     */
    public function getError()
    {
        return $this->_error ? __($this->_error) : '';
    }

    /**
     * 小程序登录
     * @param $code
     * @return bool|mixed
     */
    public function wxLogin($code)
    {
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid={$this->appid}&secret={$this->appsecret}&js_code={$code}&grant_type=authorization_code";
        $data = json_decode( curl_get($url), true);
        if(empty($data) || !isset($data['session_key']) || !isset($data['openid']))
        {
            $this->_error = $this->code[$data['errcode']];
            return false;
        }
        return $data;
    }

    /**
     * 检验数据的真实性，并且获取解密后的明文.
     * @param $encryptedData string 加密的用户数据
     * @param $iv string 与用户数据一同返回的初始向量
     * @param $data string 解密后的原文
     *
     * @return int 成功0，失败返回对应的错误码
     */
    public function decryptData( $data)
    {
        if (strlen($data['session_key']) != 24) {
            return $this->code['41001'];
        }
        $aesKey=base64_decode($data['session_key']);


        if (strlen($data['iv']) != 24) {
            return $this->code['41002'];
        }
        $aesIV=base64_decode($data['iv']);

        $aesCipher=base64_decode($data['encryptedData']);

        $result=openssl_decrypt( $aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);

        $dataObj=json_decode($result);
        if( $dataObj  == NULL )
        {
            return $this->code['41003'];
        }
        if( $dataObj->watermark->appid != $this->appid )
        {
            return $this->code['41003'];
        }
        return $dataObj;
    }

    public function decryptMobile($data)
    {
        if(!$wxData = $this->wxLogin($data['code'])) return false;
        $data = array_merge($data, $wxData);
        if(!$decryptData = $this->decryptData($data)) return false;
        return $decryptData;
    }
}